const UserModel = require('../models/UserModel')

const UserSServices = {
    add: async data => {
        return UserModel.create(data)
    },
    edit: async data => {
        if(!data.userid) {
            return Promise.reject('用户id未传，修改失败')
        }
        return UserModel.updateOne({ userid: data.userid },data)
    },
    deleteOne: async userid =>{
        if(!userid) {
            return Promise.reject('用户id未传，修改失败')
        }
        if(!await UserModel.findOne({userid})) {
            return Promise.reject('删除的数据不存在')
        }
        return UserModel.deleteOne({ userid })
    },
    queryOne: async userid => {
        if(!userid) {
            return Promise.reject('用户id未传，修改失败')
        }
        if(!await UserModel.findOne({ userid })) {
            return Promise.reject('删除的数据不存在')
        }
        return UserModel.findOne({ userid },['username','userid','role','status','email'])
    },
    query: async ({username, page,limit }) =>{
        const pattern = new RegExp(`.*${username}.*`, 'i');
        return  UserModel.find(username ?  { username: { $regex: pattern } } :{},['username','userid','role','status','email','add_time']).skip((page - 1) * limit).limit(limit)
    },
    login: async ({ email,password }) => {
        if(!email || !password) {
            return Promise.reject('邮箱或者密码未传，登录失败')
        }
        return UserModel.findOne({ email, password },['username','userid','role','status','email'])
    },
    queryCount: async ({ username }) => {
        const pattern = new RegExp(`.*${username}.*`, 'i');
        return UserModel.countDocuments(username ?  { username: { $regex: pattern } } :{})
    }
}

module.exports = UserSServices
